from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet

from .serializers import SKUSerializer, SKUIndexSerializer
from .models import SKU
# Create your views here.


# /categories/(?P<category_id>\d+)/skus?page=xxx&page_size=xxx&ordering=xxx
class GoodsListView(ListAPIView):
    """商品列表页视图"""

    # 指定序列化器
    serializer_class = SKUSerializer

    # 指定排序后端
    filter_backends = [OrderingFilter]
    # 指定排序字段
    ordering_fields = ('create_time', 'price', 'sales')

    # 重写get_queryset,指定查询集
    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        return SKU.objects.filter(category_id=category_id, is_launched=True)


class SKUSearchViewSet(HaystackViewSet):
    """SKU搜索"""

    index_models = [SKU]

    # 指定序列化器类
    serializer_class = SKUIndexSerializer
